<template>
  <el-dialog
    v-model="dialogVisible"
    title="识别信息"
    width="80%"
    :append-to-body="true"
    :destroy-on-close="false"
    :before-close="close"
    @close="close"
  >
    <div>
      <el-card class="card-container">
        <el-form :model="searchFrom">
          <el-row :gutter="24">
            <el-col :span="5">
              <el-form-item label="识别类型:" label-width="80px">
                <el-select v-model="searchFrom.type" placeholder="请选择识别类型" clearable>
                  <el-option
                    v-for="item in typeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="时间范围:" label-width="80px">
                <el-select v-model="searchFrom.range" placeholder="请选择菜单类型" clearable>
                  <el-option
                    v-for="item in rangeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="searchFrom.range == 3 || searchFrom.range == 4">
              <el-form-item label="时间:" label-width="80px">
                <el-date-picker
                  v-model="searchFrom.time"
                  type="daterange"
                  :shortcuts="shortcuts"
                  range-separator="和"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" size="small" icon="search" @click="menuSearch"
                >搜索</el-button
              >
              <el-button icon="refresh" size="small" @click="tableOrchart">{{
                !isTable ? '显示表格' : '显示曲线'
              }}</el-button>
              <el-button type="primary" size="small" icon="download" @click="menuReset"
                >数据导出</el-button
              >
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card class="card-container-bottom">
        <div v-show="isTable">
          <el-table
            :data="insectSituationList"
            row-key="id"
            :empty-text="'暂无数据'"
            stripe
            border
            height="40vh"
          >
            <el-table-column label="时间" prop="title" align="center" />
            <el-table-column label="昆虫名称" prop="name" align="center" />
            <el-table-column label="昆虫数量" prop="content" align="center" />
          </el-table>
          <pagination
            v-if="totals > 0"
            :total="totals"
            @update:current-page="handleCurrentPageUpdate"
            @update:page-size="handlePageSizeUpdate"
          ></pagination>
        </div>
        <div ref="tableChart" class="chart-container" v-show="!isTable"></div>
      </el-card>
    </div>
  </el-dialog>
</template>
<script setup lang="ts">
//系统配置
import { ref, reactive, toRefs, onMounted, onBeforeMount, watchEffect } from 'vue'

import * as echarts from 'echarts'

//业务模型
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  }
})

const state = reactive({
  searchFrom: {
    type: 1,
    range: 1,
    time: [],
    startTime: '',
    EndTime: '',
    current: 1,
    size: 10
  },
  typeList: [
    { value: 1, label: 'D2识别' },
    { value: 2, label: 'D1识别' },
    { value: 3, label: 'G识别' }
  ],
  rangeList: [
    { value: 1, label: '当前图片' },
    { value: 2, label: '当前日期' },
    { value: 3, label: '自定义日期范围(0-24时为单日)' },
    { value: 4, label: '自定义日期范围(昨12时-今12时为单日)' }
  ],
  List: [
    { date: '2025-07-14', name: '二点委夜蛾', count: '42' },
    { date: '2025-07-14', name: '铜绿异丽金龟', count: '84' },
    { date: '2025-07-14', name: '棉铃虫', count: '4' },
    { date: '2025-07-14', name: '暗黑鳃金龟', count: '24' },
    { date: '2025-07-15', name: '铜绿异丽金龟', count: '39' },
    { date: '2025-07-15', name: '小地老虎', count: '10' },
    { date: '2025-07-15', name: '二点委夜蛾', count: '26' },
    { date: '2025-07-16', name: '小地老虎', count: '10' },
    { date: '2025-07-17', name: '二点委夜蛾', count: '36' },
    { date: '2025-07-17', name: '小地老虎', count: '15' },
    { date: '2025-07-18', name: '二点委夜蛾', count: '56' }
  ],
  shortcuts: [
    {
      text: '近三天',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setDate(start.getDate() - 3)
        return [start, end]
      }
    }
  ],
  isTable: true,
  insectSituationList: [],
  totals: 0,
  chartOption: {},
  legendList: [] as string[]
})

const { searchFrom, typeList, rangeList, shortcuts, isTable, List, chartOption, legendList } =
  toRefs(state)
const dialogVisible = ref(props.dialogVisible)
const tableChart = ref()

onBeforeMount(() => {
  dialogVisible.value = props.dialogVisible
})

//分页-页码
const handleCurrentPageUpdate = (page: number) => {
  searchFrom.value.current = page
  // getList()
}
//分页-一页显示多少条
const handlePageSizeUpdate = (page: number) => {
  searchFrom.value.size = page
  // getList()
}

//列表数据

const getList = async () => {}

//图表或表格切换
const tableOrchart = () => {
  isTable.value = !isTable.value
  if (!isTable.value) {
    init()
  }
}

//画图
const init = () => {
  const { xAxisData, seriesinfo } = transformToEchartsFormat(List.value)
  chartOption.value = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: legendList.value,
      left: 'center',
      bottom: 'bottom'
    },
    grid: {
      top: 'middle',
      left: '3%',
      right: '4%',
      bottom: '3%',
      height: '80%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLine: {
        lineStyle: {}
      }
    },
    yAxis: {
      type: 'value',

      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLine: {
        show: false
      },
      nameTextStyle: {
        color: '#999'
      },
      splitArea: {
        show: false
      }
    },
    series: dynamicsSeries(seriesinfo)
  }
  //画图
  if (chartOption.value && !isTable.value) {
    const chart = echarts.init(tableChart.value)
    chart.setOption(chartOption.value)
  }
}

//整合数据格式
const transformToEchartsFormat = (data) => {
  // 1. 提取所有不重复的日期作为x轴数据
  const dateSet = new Set(data.map((item) => item.date))
  const xAxisData = Array.from(dateSet).sort()

  // 2. 提取所有昆虫种类名称
  const insectNames = [...new Set(data.map((item) => item.name))]

  // 3. 构建系列数据
  const seriesinfo = insectNames.map((name) => {
    // 按日期顺序填充数据，缺失值补0
    const seriesData = xAxisData.map((date) => {
      const item = data.find((d) => d.date === date && d.name === name)
      return item ? parseInt(item.count) : 0
    })
    return { name, type: 'line', data: seriesData }
  })
  // 4. 返回Echarts标准格式
  legendList.value = seriesinfo.map(
    (info: { name: unknown; type: string; data: number[] }) => info.name as string
  )
  return { xAxisData, seriesinfo }
}

// 动态渲染series
const dynamicsSeries = (value) => {
  return value.map((item) => {
    return {
      name: item.name,
      type: 'line',
      data: item.data,
      lineStyle: {
        normal: {
          width: 2
        }
      },
      itemStyle: {
        normal: {
          borderWidth: 2
        }
      },
      smooth: true
    }
  })
}

//关闭弹窗
// eslint-disable-next-line vue/valid-define-emits
const emit = defineEmits()
const close = async () => {
  emit('update:dialogVisible', false)
}
</script>

<style scoped>
.card-container-bottom {
  margin-top: 20px;
  width: 100%;
}
.chart-container {
  height: 50vh;
  width: 70vw;
}
</style>
